(() => {
    let cleanValue = () => {
        vmodal.style.display = "none"
        artTitle.value = ''
        chooseId = ''
        artContent.value = ''
        imgBox.src = "/img/cover.jpg"
    }

    let close = () => {
        cleanValue()
    }

    let openList = () => {
        renderList()
        chooseIsOpen ? chooseIsOpen = false : chooseIsOpen = true
        chooseIsOpen ? kindChooseUl.style.display = "block" : kindChooseUl.style.display = "none"
    }

    let choose = e => {
        if (e.target.localName = "li") {
            chooseId = e.target.dataset.id
            kindChooseIpt.value = e.target.textContent
            kindChooseUl.style.display = "none"
            chooseIsOpen = false
        }
    }

    let uploadImg = () => {
        upload.click()
    }

    let imgLoad = () => {
        var reader = new FileReader();
        // 将文件对象读取为base64的字符串
        reader.readAsDataURL(upload.files[0]);
        // 监听读取完成成的事件
        reader.onload = function (e) {
            // 一旦读取完成，就把base64的字符串赋值给base64Avatar
            imgBox.src = e.target.result
        };
    }

    async function renderList() {
        let res = await getArtList()
        console.log(res);
        let str = ''
        res.data.data.forEach(item => {
            str += `
            <li data-id=${item.id}>${item.cate_name}</li>
            `
        });
        kindChooseUl.innerHTML = str
    }

    let chooseId
    let chooseIsOpen = false
    let vmodal = document.querySelector('.v-modal')
    let closeBtn = document.querySelector('.close')
    let kindChooseIpt = document.querySelector('input[placeholder="请选择分类"]')
    let kindChooseUl = document.querySelector('.kind-choose')
    let upload = document.querySelector('.upload')
    let uploadBtn = document.querySelector('.file-choose')
    let imgBox = document.querySelector('.img-box')
    let btnGroup = document.querySelector('.button-group')
    let artTitle = document.querySelector('input[placeholder="请输入标题"]')
    let artContent = document.querySelector('.art-input')

    kindChooseIpt.addEventListener('click', openList)
    kindChooseUl.addEventListener('click', choose)
    closeBtn.addEventListener('click', close)
    uploadBtn.addEventListener('click', uploadImg)
    upload.addEventListener('change', imgLoad)
    btnGroup.addEventListener('click', async function (e) {
        if (e.target.localName = 'button') {
            let uploadObj = new FormData()
            uploadObj.append('title', artTitle.value)
            uploadObj.append('cate_id', chooseId)
            uploadObj.append('content', `<p>${artContent.value}</p>`)
            uploadObj.append('cover_img', upload.files[0])
            uploadObj.append('state', `${e.target.dataset.state}`)
            let res = await uploadArt(uploadObj)
            alert(res.data.message)
            cleanValue()
            location.reload()
        }
    })
})()